package org.example.Maskter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

public class Worker implements Runnable{

    private ConcurrentLinkedQueue<Task> workQueue;
    private ConcurrentHashMap<String,Object> resultMap;

    @Override
    public void run() {
        while(true){
            Task task = this.workQueue.poll();//领取任务
            if (task == null) {
                break;
            }
            Object result = handld(task);
            this.resultMap.put(Integer.toString(task.getId()),result);
        }
    }

    //处理任务
    private Object handld(Task task) {
        Object result = null;
        try {
            TimeUnit.MILLISECONDS.sleep(500);
            result = task.getPrice();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public void setWorkQueue(ConcurrentLinkedQueue<Task> workQueue) {
        this.workQueue = workQueue;
    }

    public void setResultMap(ConcurrentHashMap<String, Object> resultMap) {
        this.resultMap = resultMap;
    }
}
